<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>云存储管理系统 - 管理员控制台</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.9.10/dist/css/layui.css">
    <style>
        body { background: #f5f5f7; }
        .layui-header.custom-header {
            background: #1E1E1E;
            color: #fff;
            box-shadow: 0 2px 6px rgba(0,0,0,0.08);
            position: fixed;
            top: 0; left: 0; right: 0; z-index: 1001;
            height: 64px;
        }
        .custom-header .header-left {
            float: left;
            height: 64px;
            display: flex;
            align-items: center;
            font-size: 20px;
            font-weight: bold;
            letter-spacing: 2px;
            padding-left: 32px;
        }
        .custom-header .header-center {
            float: left;
            height: 64px;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            position: absolute;
            left: 0; right: 0;
            pointer-events: none;
        }
        .custom-header .search-wrap {
            width: 360px;
            margin: 0 auto;
            position: relative;
            pointer-events: all;
        }
        .custom-header .search-wrap .layui-input {
            border-radius: 18px;
            padding-left: 34px;
            background: #2A2A2A;
            border: 1px solid #444;
            color: #fff;
        }
        .custom-header .search-wrap .layui-icon-search {
            font-size: 22px;
            position: absolute;
            left: 12px;
            top: 10px;
            color: #999;
        }
        .custom-header .header-right {
            float: right;
            height: 64px;
            display: flex;
            align-items: center;
            padding-right: 36px;
        }
        .custom-header .user-name {
            font-size: 16px;
            color: #fff;
            margin-right: 16px;
        }
        .custom-header .admin-badge {
            background: #FF5722;
            color: #fff;
            padding: 2px 8px;
            border-radius: 8px;
            font-size: 12px;
            margin-right: 12px;
        }
        .custom-header .now-time {
            color: #f4f4f4;
            font-size: 14px;
            margin-right: 16px;
            margin-left: 12px;
        }
        .custom-header .logout-btn {
            background: #FF5722 !important;
            color: #fff !important;
            border-radius: 16px;
            margin-left: 8px;
            padding: 0 16px;
        }
        .layui-side.custom-side {
            top: 64px;
            background: #2C3E50 !important;
            width: 240px;
            color: #fff;
        }
        .layui-nav.custom-nav .layui-nav-item > a {
            color: #BDC3C7;
            font-size: 16px;
        }
        .layui-nav.custom-nav .layui-nav-child a {
            color: #fff !important;
            font-size: 15px;
        }
        .layui-nav.custom-nav .layui-nav-itemed > a,
        .layui-nav.custom-nav .layui-this > a {
            background: #34495E !important;
            color: #fff !important;
        }
        .layui-nav.custom-nav .layui-nav-child dd.layui-this a {
            background: #E74C3C !important;
            color: #fff !important;
        }
        .custom-main {
            margin-left: 240px;
            margin-top: 80px;
            padding: 32px 32px 32px 32px;
            min-height: 600px;
        }
        .layui-card {margin-bottom: 16px;}
        .layui-table-view {margin-bottom: 0;}
        .layui-badge {font-size: 13px;}
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 24px;
            border-radius: 8px;
            text-align: center;
        }
        .stat-card.users { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .stat-card.files { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
        .stat-card.storage { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        .stat-card.transfers { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 8px;
        }
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
    </style>
</head>
<body class="layui-layout-body">

<!-- 顶部栏 -->
<div class="layui-header custom-header">
    <div class="header-left">
        <span>云存储管理系统</span>
    </div>
    <div class="header-center">
        <div class="search-wrap">
            <i class="layui-icon layui-icon-search"></i>
            <input type="text" name="systemSearch" id="search-input" placeholder="搜索用户、文件、日志..." autocomplete="off" class="layui-input" style="width: 100%;">
        </div>
    </div>
    <div class="header-right">
        <span class="now-time" id="now-time"></span>
        <span class="admin-badge">管理员</span>
        <span class="user-name" id="admin-name">管理员</span>
        <button class="layui-btn logout-btn" id="btn-logout">退出</button>
    </div>
    <div style="clear: both;"></div>
</div>

<!-- 侧边栏 -->
<div class="layui-side custom-side">
    <div class="layui-side-scroll">
        <ul class="layui-nav layui-nav-tree custom-nav" lay-filter="admin-side">
            <li class="layui-nav-item layui-nav-itemed">
                <a href="javascript:;">系统概览</a>
                <dl class="layui-nav-child">
                    <dd class="layui-this"><a href="javascript:;" id="btn-dashboard">仪表盘</a></dd>
                    <dd><a href="javascript:;" id="btn-statistics">统计分析</a></dd>
                    <dd><a href="javascript:;" id="btn-performance">性能监控</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item">
                <a href="javascript:;">用户管理</a>
                <dl class="layui-nav-child">
                    <dd><a href="javascript:;" id="btn-user-list">用户列表</a></dd>
                    <dd><a href="javascript:;" id="btn-user-roles">角色权限</a></dd>
                    <dd><a href="javascript:;" id="btn-user-activity">用户活动</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item">
                <a href="javascript:;">文件管理</a>
                <dl class="layui-nav-child">
                    <dd><a href="javascript:;" id="btn-all-files">所有文件</a></dd>
                    <dd><a href="javascript:;" id="btn-file-integrity">完整性检查</a></dd>
                    <dd><a href="javascript:;" id="btn-storage-quota">存储配额</a></dd>
                    <dd><a href="javascript:;" id="btn-file-upload-manage">上传管理</a></dd>
                    <dd><a href="javascript:;" id="btn-file-download">下载管理</a></dd>
                    <dd><a href="javascript:;" id="btn-file-trash">回收站管理</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item">
                <a href="javascript:;" id="btn-system-logs">系统日志</a>
            </li>
            <li class="layui-nav-item">
                <a href="javascript:;">系统配置</a>
                <dl class="layui-nav-child">
                    <dd><a href="javascript:;" id="btn-security-config">安全配置</a></dd>
                    <dd><a href="javascript:;" id="btn-service-status">服务状态</a></dd>
                    <dd><a href="javascript:;" id="btn-backup-config">备份配置</a></dd>
                </dl>
            </li>
        </ul>
    </div>
</div>

<!-- 主体内容区 -->
<div class="custom-main" id="main-container">
    <div id="dashboard-panel"></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/layui@2.9.10/dist/layui.js"></script>
<script>
    layui.use(['element','layer','table','upload','form'], function(){
        var $ = layui.jquery, element = layui.element, layer = layui.layer, table = layui.table, upload = layui.upload, form = layui.form;
        
        // 获取当前用户角色
        var currentUserRole = 'ADMIN'; // 默认为普通管理员
        function getCurrentUserRole() {
            // 通过Ajax获取当前用户角色
            $.ajax({
                url: '/auth/status',
                type: 'GET',
                async: false, // 同步请求
                success: function(response) {
                    if (response.userRole) {
                        currentUserRole = response.userRole;
                    }
                }
            });
            return currentUserRole;
        }

        // 真实数据，通过API获取
        var systemStats = {
            totalUsers: 0,
            totalFiles: 0,
            totalStorage: "0MB",
            activeTransfers: 0
        };

        var users = [];
        var systemFiles = [];

        // 获取JWT Token
        function getToken() {
            return localStorage.getItem('token') || sessionStorage.getItem('token');
        }

        // 验证Token是否有效
        function isTokenValid(token) {
            if (!token) return false;
            
            try {
                // 简单的JWT解析检查过期时间
                const payload = JSON.parse(atob(token.split('.')[1]));
                const currentTime = Math.floor(Date.now() / 1000);
                return payload.exp > currentTime;
            } catch (e) {
                return false;
            }
        }

        // 检查并处理token失效
        function checkTokenAndRedirect() {
            const token = getToken();
            if (!token || !isTokenValid(token)) {
                layer.msg('登录已过期，请重新登录', {icon: 2});
                setTimeout(() => {
                    window.location.href = '/auth/admin-login';
                }, 1500);
                return false;
            }
            return true;
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + sizes[i];
        }

        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '';
            const date = new Date(dateTime);
            return date.getFullYear() + '-' + 
                   String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                   String(date.getDate()).padStart(2, '0') + ' ' +
                   String(date.getHours()).padStart(2, '0') + ':' + 
                   String(date.getMinutes()).padStart(2, '0') + ':' + 
                   String(date.getSeconds()).padStart(2, '0');
        }

        // 格式化日期
        function formatDate(dateTime) {
            if (!dateTime) return '';
            const date = new Date(dateTime);
            return date.getFullYear() + '-' + 
                   String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                   String(date.getDate()).padStart(2, '0');
        }

        // 获取文件类型
        function getFileType(filename) {
            if (!filename) return '未知';
            const ext = filename.split('.').pop().toLowerCase();
            const types = {
                'pdf': 'PDF文档',
                'doc': 'Word文档',
                'docx': 'Word文档',
                'xls': 'Excel表格',
                'xlsx': 'Excel表格',
                'ppt': 'PowerPoint',
                'pptx': 'PowerPoint',
                'txt': '文本文件',
                'jpg': '图片',
                'jpeg': '图片',
                'png': '图片',
                'gif': '图片',
                'zip': '压缩包',
                'rar': '压缩包',
                '7z': '压缩包',
                'mp4': '视频',
                'avi': '视频',
                'mkv': '视频',
                'mp3': '音频',
                'wav': '音频',
                'flac': '音频'
            };
            return types[ext] || '其他';
        }

        // 获取系统统计信息
        function loadSystemDashboard() {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                window.location.href = '/auth/admin-login';
                return;
            }

            $.ajax({
                url: '/api/admin/dashboard',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const data = res.data;
                        systemStats = {
                            totalUsers: data.userStats.totalUsers,
                            totalFiles: data.storageStats.totalFiles,
                            totalStorage: formatFileSize(data.storageStats.totalSize),
                            activeTransfers: data.serviceStatus.activeServices || 0
                        };
                        // 重新渲染仪表板
                        renderDashboard();
                        // 加载实时数据
                        loadRecentActivities();
                        loadSystemStatus();
                    }
                },
                error: function() {
                    layer.msg('获取系统统计失败', {icon: 2});
                }
            });
        }

        // 加载最近活动
        function loadRecentActivities() {
            const token = getToken();
            if (!token) return;

            $.ajax({
                url: '/api/admin/logs/recent-activities',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const data = res.data;
                        let rows = '';
                        
                        // 处理用户操作日志
                        if (data.userOperations && data.userOperations.length > 0) {
                            data.userOperations.forEach(log => {
                                const time = formatTimeAgo(log.operationTime);
                                rows += `<tr><td>${log.user?.username || 'unknown'}</td><td>${log.operation}</td><td>${time}</td></tr>`;
                            });
                        }
                        
                        // 处理文件操作日志
                        if (data.fileOperations && data.fileOperations.length > 0) {
                            data.fileOperations.forEach(log => {
                                const time = formatTimeAgo(log.operationTime);
                                rows += `<tr><td>${log.user?.username || 'unknown'}</td><td>${log.operationType}</td><td>${time}</td></tr>`;
                            });
                        }
                        
                        if (rows === '') {
                            rows = '<tr><td colspan="3">暂无活动记录</td></tr>';
                        }
                        
                        $('#recent-activities').html(rows);
                    }
                },
                error: function() {
                    $('#recent-activities').html('<tr><td colspan="3">加载失败</td></tr>');
                }
            });
        }

        // 加载系统状态
        function loadSystemStatus() {
            const token = getToken();
            if (!token) return;

            $.ajax({
                url: '/api/admin/services',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const services = res.data;
                        let statusHtml = '';
                        
                        services.forEach(service => {
                            const statusClass = service.status === 'RUNNING' ? 'layui-bg-green' : 'layui-bg-red';
                            const statusText = service.status === 'RUNNING' ? '正常' : '异常';
                            statusHtml += `<p><span class="layui-badge ${statusClass}">${statusText}</span> ${service.name}</p>`;
                        });
                        
                        if (statusHtml === '') {
                            statusHtml = '<p>暂无服务状态信息</p>';
                        }
                        
                        $('#system-status').html(statusHtml);
                    }
                },
                error: function() {
                    $('#system-status').html('<p>加载失败</p>');
                }
            });
        }

        // 格式化时间为相对时间
        function formatTimeAgo(dateTime) {
            if (!dateTime) return '';
            const now = new Date();
            const date = new Date(dateTime);
            const diffMs = now - date;
            const diffMins = Math.floor(diffMs / 60000);
            const diffHours = Math.floor(diffMins / 60);
            const diffDays = Math.floor(diffHours / 24);
            
            if (diffMins < 1) return '刚刚';
            if (diffMins < 60) return `${diffMins}分钟前`;
            if (diffHours < 24) return `${diffHours}小时前`;
            if (diffDays < 7) return `${diffDays}天前`;
            return formatDateTime(dateTime);
        }

        function updateTime(){
            var now = new Date();
            var str = now.getFullYear()+'-'+
                ('0'+(now.getMonth()+1)).slice(-2)+'-'+
                ('0'+now.getDate()).slice(-2)+' '+
                ('0'+now.getHours()).slice(-2)+':'+
                ('0'+now.getMinutes()).slice(-2)+':'+
                ('0'+now.getSeconds()).slice(-2);
            document.getElementById("now-time").innerText = str;
        }
        updateTime(); setInterval(updateTime, 1000);

        // 页面初始化 - 加载真实数据
        loadSystemDashboard();

        // 顶部搜索
        $('#search-input').on('keydown', function(e){
            if(e.keyCode === 13){
                var val = $(this).val();
                layer.msg('搜索关键词: ' + val);
                return false;
            }
        });

        // 菜单切换
        $('#btn-dashboard').click(function(){
            setActiveMenu(this);
            renderDashboard();
        });
        $('#btn-statistics').click(function(){
            setActiveMenu(this);
            renderStatistics();
        });
        $('#btn-performance').click(function(){
            setActiveMenu(this);
            renderPerformance();
        });
        $('#btn-user-list').click(function(){
            setActiveMenu(this);
            renderUserList();
        });
        $('#btn-create-admin').click(function(){
            showCreateAdminDialog();
        });
        $('#btn-user-roles').click(function(){
            setActiveMenu(this);
            renderUserRoles();
        });
        $('#btn-user-activity').click(function(){
            setActiveMenu(this);
            renderUserActivity();
        });
        $('#btn-all-files').click(function(){
            setActiveMenu(this);
            renderAllFiles();
        });
        $('#btn-file-integrity').click(function(){
            setActiveMenu(this);
            renderFileIntegrity();
        });
        $('#btn-storage-quota').click(function(){
            setActiveMenu(this);
            renderStorageQuota();
        });
        $('#btn-system-logs').click(function(){
            setActiveMenu(this);
            renderSystemLogs();
        });
        $('#btn-security-config').click(function(){
            setActiveMenu(this);
            renderSecurityConfig();
        });
        $('#btn-service-status').click(function(){
            setActiveMenu(this);
            renderServiceStatus();
        });
        $('#btn-backup-config').click(function(){
            setActiveMenu(this);
            renderBackupConfig();
        });
        $('#btn-file-upload-manage').click(function(){
            setActiveMenu(this);
            renderFileUploadManage();
        });
        $('#btn-file-download').click(function(){
            setActiveMenu(this);
            renderFileDownloadManage();
        });
        $('#btn-file-trash').click(function(){
            setActiveMenu(this);
            renderFileTrashManage();
        });

        $('#btn-logout').click(function(){
            layer.confirm('确定要退出管理员控制台吗？', {icon: 3, title:'提示'}, function(index){
                window.location.href = '/auth/admin-login';
                layer.close(index);
            });
        });

        function setActiveMenu(element) {
            $('.layui-nav-child dd').removeClass('layui-this');
            $('.layui-nav-item').removeClass('layui-this');
            $(element).parent().addClass('layui-this');
            $(element).closest('.layui-nav-item').addClass('layui-nav-itemed');
        }

        // 仪表盘
        function renderDashboard(){
            $('#main-container').html(`
        <div class="stats-grid">
            <div class="stat-card users">
                <div class="stat-number">${systemStats.totalUsers}</div>
                <div class="stat-label">总用户数</div>
            </div>
            <div class="stat-card files">
                <div class="stat-number">${systemStats.totalFiles}</div>
                <div class="stat-label">总文件数</div>
            </div>
            <div class="stat-card storage">
                <div class="stat-number">${systemStats.totalStorage}</div>
                <div class="stat-label">存储空间</div>
            </div>
            <div class="stat-card transfers">
                <div class="stat-number">${systemStats.activeTransfers}</div>
                <div class="stat-label">活跃传输</div>
            </div>
        </div>
        <div class="layui-row layui-col-space16">
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header">最新用户活动</div>
                    <div class="layui-card-body">
                        <table class="layui-table" lay-size="sm">
                            <thead>
                                <tr>
                                    <th>用户</th>
                                    <th>操作</th>
                                    <th>时间</th>
                                </tr>
                            </thead>
                            <tbody id="recent-activities">
                                <tr><td colspan="3">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header">系统状态</div>
                    <div class="layui-card-body">
                        <div style="padding: 16px;" id="system-status">
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        `);
        }

        // 用户列表
        function renderUserList(){
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">
                用户管理
                <span style="float:right;">
                    <button class="layui-btn layui-btn-sm layui-btn-normal" id="btn-add-user">👤 添加用户</button>
                </span>
            </div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 50px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载用户数据
            $.ajax({
                url: '/api/admin/users',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const users = res.data;
                        let rows = '';
                        
                        users.forEach(user => {
                            const statusClass = user.isActive ? 'layui-bg-green' : 'layui-bg-red';
                            const statusText = user.isActive ? '激活' : '禁用';
                            const roleText = user.roles && user.roles.length > 0 ? user.roles[0] : 'USER';
                            const lastLogin = user.updatedAt ? formatDateTime(user.updatedAt) : '未登录';
                            
                            rows += `<tr>
                                <td>${user.userId}</td>
                                <td>${user.username}</td>
                                <td>${roleText}</td>
                                <td><span class="layui-badge ${statusClass}">${statusText}</span></td>
                                <td>${lastLogin}</td>
                                <td>${user.email || '-'}</td>
                                <td>
                                    <button class="layui-btn layui-btn-xs layui-btn-normal btn-edit-user" data-id="${user.userId}">编辑</button>
                                    <button class="layui-btn layui-btn-xs ${user.isActive ? 'layui-btn-danger' : 'layui-btn-normal'} btn-toggle-user" data-id="${user.userId}">${user.isActive ? '禁用' : '启用'}</button>
                                    <button class="layui-btn layui-btn-xs layui-btn-warm btn-reset-password" data-id="${user.userId}">重置密码</button>
                                </td>
                            </tr>`;
                        });
                        
                        if (rows === '') {
                            rows = '<tr><td colspan="7">暂无用户数据</td></tr>';
                        }
                        
                        $('#main-container').html(`
                    <div class="layui-card">
                        <div class="layui-card-header">
                            用户管理
                            <span style="float:right;">
                                <button class="layui-btn layui-btn-sm layui-btn-normal" id="btn-add-user">👤 添加用户</button>
                            </span>
                        </div>
                        <div class="layui-card-body">
                            <table class="layui-table" lay-size="sm">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>用户名</th>
                                        <th>角色</th>
                                        <th>状态</th>
                                        <th>最后登录</th>
                                        <th>邮箱</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>${rows}</tbody>
                            </table>
                        </div>
                    </div>
                    `);
                        
                        // 绑定事件处理程序
                        bindUserManagementEvents();
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    console.error('加载用户列表失败:', xhr, textStatus, errorThrown);
                    
                    let errorMessage = '加载用户列表失败';
                    
                    if (textStatus === 'timeout') {
                        errorMessage = '请求超时，请重试';
                    } else if (xhr.status === 401) {
                        errorMessage = '登录已过期，请重新登录';
                        // 清除token并跳转到登录页
                        localStorage.removeItem('token');
                        window.location.href = '/login';
                        return;
                    } else if (xhr.status === 403) {
                        errorMessage = '权限不足';
                    } else if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    } else if (xhr.status === 0) {
                        errorMessage = '网络连接失败，请检查网络';
                    }
                    
                    // 显示错误页面
                    $('#main-container').html(`
                        <div class="layui-card">
                            <div class="layui-card-header">用户管理</div>
                            <div class="layui-card-body">
                                <div style="text-align: center; padding: 50px;">
                                    <i class="layui-icon layui-icon-face-cry" style="font-size: 60px; color: #ff5722;"></i>
                                    <p style="font-size: 16px; margin-top: 20px;">${errorMessage}</p>
                                    <button class="layui-btn layui-btn-primary" onclick="renderUserList()">
                                        <i class="layui-icon layui-icon-refresh"></i> 重新加载
                                    </button>
                                </div>
                            </div>
                        </div>
                    `);
                    
                    layer.msg(errorMessage, {icon: 2, time: 3000});
                },
                timeout: 10000 // 10秒超时
            });
        }

        // 绑定用户管理事件
        function bindUserManagementEvents() {
            $('.btn-edit-user').click(function(){
                const userId = $(this).data('id');
                editUser(userId);
            });
            
            $('.btn-toggle-user').click(function(){
                const userId = $(this).data('id');
                toggleUserStatus(userId);
            });
            
            $('.btn-reset-password').click(function(){
                const userId = $(this).data('id');
                resetUserPassword(userId);
            });
            
            $('#btn-add-user').click(function(){
                layer.msg('添加用户功能开发中', {icon: 1});
            });
        }

        // 编辑用户
        function editUser(userId) {
            layer.msg('编辑用户功能开发中', {icon: 1});
        }

        // 切换用户状态
        function toggleUserStatus(userId) {
            if (!checkTokenAndRedirect()) return;
            
            const token = getToken();
            if (!token) return;
            
            // 检查是否已经在处理中，防止重复点击
            const toggleBtn = $(`.btn-toggle-user[data-id="${userId}"]`);
            if (toggleBtn.hasClass('layui-btn-disabled')) {
                return;
            }
            
            layer.confirm('确定要切换用户状态吗？', {icon: 3, title: '确认'}, function(index) {
                // 设置按钮为禁用状态，防止重复点击
                toggleBtn.addClass('layui-btn-disabled').prop('disabled', true);
                
                // 显示加载提示
                const loadingIndex = layer.load(1, {
                    shade: [0.1,'#fff']
                });
                
                $.ajax({
                    url: `/api/admin/users/${userId}/status`,
                    type: 'PUT',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    },
                    timeout: 10000, // 10秒超时
                    success: function(res) {
                        layer.close(loadingIndex);
                        
                        if (res.success) {
                            layer.msg(res.message, {icon: 1});
                            
                            // 使用局部更新而不是完整刷新
                            updateUserStatusInTable(userId, res.isActive);
                            
                        } else {
                            layer.msg(res.message || '操作失败', {icon: 2});
                        }
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        layer.close(loadingIndex);
                        console.error('切换用户状态失败:', xhr, textStatus, errorThrown);
                        
                        let errorMessage = '操作失败';
                        
                        if (textStatus === 'timeout') {
                            errorMessage = '请求超时，请重试';
                        } else if (xhr.status === 401) {
                            errorMessage = '登录已过期，请重新登录';
                            // 清除token并跳转到登录页
                            localStorage.removeItem('token');
                            window.location.href = '/login';
                            return;
                        } else if (xhr.status === 403) {
                            errorMessage = '权限不足';
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMessage = xhr.responseJSON.message;
                        } else if (xhr.status === 0) {
                            errorMessage = '网络连接失败，请检查网络';
                        }
                        
                        layer.msg(errorMessage, {icon: 2, time: 3000});
                    },
                    complete: function() {
                        // 恢复按钮状态
                        toggleBtn.removeClass('layui-btn-disabled').prop('disabled', false);
                    }
                });
                layer.close(index);
            });
        }
        
        // 更新表格中的用户状态（局部更新）
        function updateUserStatusInTable(userId, isActive) {
            try {
                const userRow = $(`.btn-toggle-user[data-id="${userId}"]`).closest('tr');
                if (userRow.length > 0) {
                    // 更新状态徽章
                    const statusBadge = userRow.find('.layui-badge');
                    const statusClass = isActive ? 'layui-bg-green' : 'layui-bg-red';
                    const statusText = isActive ? '激活' : '禁用';
                    statusBadge.removeClass('layui-bg-green layui-bg-red').addClass(statusClass).text(statusText);
                    
                    // 更新切换按钮
                    const toggleBtn = $(`.btn-toggle-user[data-id="${userId}"]`);
                    const buttonClass = isActive ? 'layui-btn-danger' : 'layui-btn-normal';
                    const buttonText = isActive ? '禁用' : '启用';
                    toggleBtn.removeClass('layui-btn-danger layui-btn-normal').addClass(buttonClass).text(buttonText);
                    
                    console.log(`用户状态已更新: userId=${userId}, isActive=${isActive}`);
                } else {
                    console.warn(`未找到用户行: userId=${userId}, 将重新加载用户列表`);
                    // 如果找不到用户行，则重新加载整个列表
                    setTimeout(() => renderUserList(), 500);
                }
            } catch (error) {
                console.error('更新用户状态时发生错误:', error);
                // 出错时重新加载列表
                setTimeout(() => renderUserList(), 500);
            }
        }

        // 重置用户密码
        function resetUserPassword(userId) {
            if (!checkTokenAndRedirect()) return;
            
            const token = getToken();
            if (!token) return;
            
            // 检查是否已经在处理中，防止重复点击
            const resetBtn = $(`.btn-reset-password[data-id="${userId}"]`);
            if (resetBtn.hasClass('layui-btn-disabled')) {
                return;
            }
            
            layer.confirm('确定要重置用户密码吗？重置后将生成随机密码。', {icon: 3, title: '确认'}, function(index) {
                // 设置按钮为禁用状态，防止重复点击
                resetBtn.addClass('layui-btn-disabled').prop('disabled', true);
                
                // 显示加载提示
                const loadingIndex = layer.load(1, {
                    shade: [0.1,'#fff']
                });
                
                $.ajax({
                    url: `/api/admin/users/${userId}/reset-password`,
                    type: 'POST',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    },
                    timeout: 10000, // 10秒超时
                    success: function(res) {
                        layer.close(loadingIndex);
                        
                        if (res.success) {
                            layer.alert(`密码重置成功！<br/><br/>新密码：<span style="color:red;font-weight:bold;font-size:16px;">${res.newPassword}</span><br/><br/>请及时告知用户并要求其尽快修改密码。`, {
                                icon: 1,
                                title: '密码重置成功',
                                area: ['400px', '250px']
                            });
                        } else {
                            layer.msg(res.message || '重置密码失败', {icon: 2});
                        }
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        layer.close(loadingIndex);
                        console.error('重置密码失败:', xhr, textStatus, errorThrown);
                        
                        let errorMessage = '重置密码失败';
                        
                        if (textStatus === 'timeout') {
                            errorMessage = '请求超时，请重试';
                        } else if (xhr.status === 401) {
                            errorMessage = '登录已过期，请重新登录';
                            // 清除token并跳转到登录页
                            localStorage.removeItem('token');
                            window.location.href = '/login';
                            return;
                        } else if (xhr.status === 403) {
                            errorMessage = '权限不足';
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMessage = xhr.responseJSON.message;
                        } else if (xhr.status === 0) {
                            errorMessage = '网络连接失败，请检查网络';
                        }
                        
                        layer.msg(errorMessage, {icon: 2, time: 3000});
                    },
                    complete: function() {
                        // 恢复按钮状态
                        resetBtn.removeClass('layui-btn-disabled').prop('disabled', false);
                    }
                });
                layer.close(index);
            });
        }

        // 系统文件管理
        function renderAllFiles(){
            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">系统文件管理</div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 40px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px;"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载系统文件
            loadAllFiles();
        }

        // 加载所有文件
        function loadAllFiles() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping all files load');
                return;
            }

            $.ajax({
                url: '/api/admin/files',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        renderAllFilesTable(res.data);
                    } else {
                        layer.msg('获取系统文件失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取系统文件失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        window.location.href = '/auth/admin-login';
                    } else {
                        layer.msg('获取系统文件失败', {icon: 2});
                    }
                }
            });
        }

        // 渲染所有文件表格
        function renderAllFilesTable(files) {
            var rows = '';
            for(var i=0;i<files.length;i++){
                var f = files[i];
                var statusClass = f.isDeleted ? 'layui-bg-red' : 'layui-bg-green';
                var statusText = f.isDeleted ? '已删除' : '正常';
                rows += `<tr>
                <td>${f.fileId}</td>
                <td>${f.originalFilename}</td>
                <td>${f.uploaderName || '未知用户'}</td>
                <td>${f.fileSizeFormatted || '未知'}</td>
                <td>${getFileType(f.originalFilename)}</td>
                <td>${formatDate(f.createdAt)}</td>
                <td><span class="layui-badge ${statusClass}">${statusText}</span></td>
                <td>
                    <button class="layui-btn layui-btn-xs layui-btn-primary btn-download-file" data-id="${f.fileId}">下载</button>
                    <button class="layui-btn layui-btn-xs layui-btn-danger btn-delete-file" data-id="${f.fileId}">删除</button>
                </td>
            </tr>`;
            }
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">系统文件管理</div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>文件名</th>
                            <th>上传者</th>
                            <th>大小</th>
                            <th>类型</th>
                            <th>上传时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        </div>
        `);

            $('.btn-download-file').click(function(){
                var fileId = $(this).data('id');
                adminDownloadFile(fileId);
            });
            $('.btn-delete-file').click(function(){
                var fileId = $(this).data('id');
                layer.confirm('确定要删除该文件吗？', {icon: 3, title:'警告'}, function(index){
                    adminDeleteFile(fileId);
                    layer.close(index);
                });
            });
        }

        // 管理员下载文件
        function adminDownloadFile(fileId) {
            const token = getToken();
            if (!token) {
                layer.msg('认证失败', {icon: 2});
                return;
            }

            window.open('/api/files/download/' + fileId + '?token=' + token, '_blank');
        }

        // 管理员删除文件
        function adminDeleteFile(fileId) {
            const token = getToken();
            if (!token) {
                layer.msg('认证失败', {icon: 2});
                return;
            }

            $.ajax({
                url: '/api/files/' + fileId + '?permanent=true',
                type: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        layer.msg('文件删除成功', {icon: 1});
                        loadAllFiles(); // 重新加载列表
                    } else {
                        layer.msg('删除失败: ' + res.message, {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log('删除文件失败:', error, 'status:', xhr.status);
                    layer.msg('删除文件失败', {icon: 2});
                }
            });
        }

        // 系统日志
        function renderSystemLogs(){
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">
                系统日志
                <span style="float:right;">
                    <button class="layui-btn layui-btn-sm layui-btn-normal" id="btn-refresh-logs">刷新</button>
                    <button class="layui-btn layui-btn-sm layui-btn-warm" id="btn-export-logs">导出</button>
                </span>
            </div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 50px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载日志数据
            loadSystemLogsData();
        }

        // 加载系统日志数据
        function loadSystemLogsData() {
            const token = getToken();
            if (!token) return;

            $.ajax({
                url: '/api/admin/logs/user-operations',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const logs = res.data;
                        let rows = '';
                        
                        logs.forEach(log => {
                            const time = formatDateTime(log.operationTime);
                            const levelClass = getLevelClass(log.operationType);
                            const levelText = log.operationType;
                            const username = log.user?.username || 'unknown';
                            
                            rows += `<tr>
                                <td>${time}</td>
                                <td><span class="layui-badge ${levelClass}">${levelText}</span></td>
                                <td>用户操作</td>
                                <td>${username}</td>
                                <td>${log.operation}</td>
                                <td>${log.operationDetails || '-'}</td>
                            </tr>`;
                        });
                        
                        if (rows === '') {
                            rows = '<tr><td colspan="6">暂无日志数据</td></tr>';
                        }
                        
                        $('#main-container').html(`
                    <div class="layui-card">
                        <div class="layui-card-header">
                            系统日志
                            <span style="float:right;">
                                <button class="layui-btn layui-btn-sm layui-btn-normal" id="btn-refresh-logs">刷新</button>
                                <button class="layui-btn layui-btn-sm layui-btn-warm" id="btn-export-logs">导出</button>
                            </span>
                        </div>
                        <div class="layui-card-body">
                            <table class="layui-table" lay-size="sm">
                                <thead>
                                    <tr>
                                        <th>时间</th>
                                        <th>级别</th>
                                        <th>模块</th>
                                        <th>用户</th>
                                        <th>操作</th>
                                        <th>详情</th>
                                    </tr>
                                </thead>
                                <tbody>${rows}</tbody>
                            </table>
                        </div>
                    </div>
                    `);
                        
                        // 绑定事件
                        $('#btn-refresh-logs').click(function() {
                            renderSystemLogs();
                        });
                        
                        $('#btn-export-logs').click(function() {
                            layer.msg('导出功能开发中', {icon: 1});
                        });
                    }
                },
                error: function() {
                    layer.msg('加载日志失败', {icon: 2});
                }
            });
        }

        // 获取日志级别样式
        function getLevelClass(operationType) {
            switch(operationType) {
                case 'LOGIN':
                case 'LOGOUT':
                    return 'layui-bg-blue';
                case 'UPLOAD':
                case 'DOWNLOAD':
                    return 'layui-bg-green';
                case 'DELETE':
                    return 'layui-bg-red';
                case 'MODIFY':
                case 'SHARE':
                    return 'layui-bg-orange';
                default:
                    return 'layui-bg-gray';
            }
        }

        // 服务状态
        function renderServiceStatus(){
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">
                服务状态监控
                <span style="float:right;">
                    <button class="layui-btn layui-btn-sm layui-btn-normal" id="btn-refresh-services">刷新</button>
                </span>
            </div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 50px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载服务状态数据
            loadServiceStatusData();
        }

        // 加载服务状态数据
        function loadServiceStatusData() {
            const token = getToken();
            if (!token) return;

            $.ajax({
                url: '/api/admin/services',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const services = res.data;
                        let rows = '';
                        
                        services.forEach(service => {
                            let statusClass, statusText;
                            
                            switch(service.status) {
                                case 'RUNNING':
                                    statusClass = 'layui-bg-green';
                                    statusText = '运行中';
                                    break;
                                case 'DEBUGGING':
                                    statusClass = 'layui-bg-orange';
                                    statusText = '调试中';
                                    break;
                                case 'STOPPED':
                                    statusClass = 'layui-bg-red';
                                    statusText = '停止';
                                    break;
                                case 'ERROR':
                                    statusClass = 'layui-bg-red';
                                    statusText = '错误';
                                    break;
                                default:
                                    statusClass = 'layui-bg-gray';
                                    statusText = '未知';
                            }
                            
                            const updateTime = service.lastUpdate ? formatDateTime(service.lastUpdate) : '未知';
                            
                            rows += `<tr>
                                <td>${service.name}</td>
                                <td><span class="layui-badge ${statusClass}">${statusText}</span></td>
                                <td>${service.priority || '-'}</td>
                                <td>${service.description || '-'}</td>
                                <td>${updateTime}</td>
                                <td>
                                    <button class="layui-btn layui-btn-xs btn-restart-service" data-id="${service.id}">重启</button>
                                </td>
                            </tr>`;
                        });
                        
                        if (rows === '') {
                            rows = '<tr><td colspan="6">暂无服务状态数据</td></tr>';
                        }
                        
                        $('#main-container').html(`
                    <div class="layui-card">
                        <div class="layui-card-header">
                            服务状态监控
                            <span style="float:right;">
                                <button class="layui-btn layui-btn-sm layui-btn-normal" id="btn-refresh-services">刷新</button>
                            </span>
                        </div>
                        <div class="layui-card-body">
                            <table class="layui-table" lay-size="sm">
                                <thead>
                                    <tr>
                                        <th>服务名称</th>
                                        <th>状态</th>
                                        <th>优先级</th>
                                        <th>描述</th>
                                        <th>最后更新</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>${rows}</tbody>
                            </table>
                        </div>
                    </div>
                    `);
                        
                        // 绑定事件
                        $('#btn-refresh-services').click(function() {
                            renderServiceStatus();
                        });
                        
                        $('.btn-restart-service').click(function() {
                            const serviceId = $(this).data('id');
                            layer.msg('服务重启功能开发中', {icon: 1});
                        });
                    }
                },
                error: function() {
                    layer.msg('加载服务状态失败', {icon: 2});
                }
            });
        }

        // 文件上传管理
        function renderFileUploadManage(){
            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">文件上传管理</div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 40px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px;"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载上传文件管理
            loadUploadFiles();
        }

        // 加载上传文件
        function loadUploadFiles() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping upload files load');
                return;
            }

            $.ajax({
                url: '/api/admin/upload-logs',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        renderUploadFilesTable(res.data);
                    } else {
                        layer.msg('获取上传文件失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取上传文件失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        window.location.href = '/auth/admin-login';
                    } else {
                        layer.msg('获取上传文件失败', {icon: 2});
                    }
                }
            });
        }

        // 渲染上传文件表格
        function renderUploadFilesTable(logs) {
            var rows = '';
            
            // 如果没有数据，显示提示信息
            if (logs.length === 0) {
                rows = `
                    <tr>
                        <td colspan="6" style="text-align: center; color: #999;">
                            暂无上传日志数据
                        </td>
                    </tr>
                `;
            } else {
                for(var i=0;i<logs.length;i++){
                    var log = logs[i];
                    var encryptClass = log.isEncrypted ? 'layui-bg-orange' : 'layui-bg-gray';
                    var encryptText = log.isEncrypted ? '已加密' : '未加密';
                    rows += `<tr>
                    <td>${log.originalFilename || '未知文件'}</td>
                    <td>${log.uploaderName || '未知用户'}</td>
                    <td>${log.userTags || '无'}</td>
                    <td><span class="layui-badge ${encryptClass}">${encryptText}</span></td>
                    <td>${log.fileSizeFormatted || '未知'}</td>
                    <td>${formatDateTime(log.operationTime)}</td>
                </tr>`;
                }
            }
            
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">文件上传管理</div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>上传者</th>
                            <th>标签</th>
                            <th>加密状态</th>
                            <th>大小</th>
                            <th>上传时间</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        </div>
        `);
        }

        // 显示文件详情
        function showFileDetail(fileId) {
            layer.msg('文件详情功能待实现', {icon: 0});
        }

        // 文件下载管理
        function renderFileDownloadManage(){
            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">文件下载管理</div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 40px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px;"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载下载管理
            loadDownloadLogs();
        }

        // 加载下载日志
        function loadDownloadLogs() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping download logs load');
                return;
            }

            $.ajax({
                url: '/api/admin/download-logs',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        renderDownloadLogsTable(res.data);
                    } else {
                        // 如果API不存在，显示静态数据
                        console.log('下载日志API不存在，显示静态数据');
                        renderDownloadLogsTable([]);
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取下载日志失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        window.location.href = '/auth/admin-login';
                    } else if (xhr.status === 404) {
                        // API不存在，显示静态数据
                        console.log('下载日志API不存在，显示静态数据');
                        renderDownloadLogsTable([]);
                    } else {
                        layer.msg('获取下载日志失败', {icon: 2});
                    }
                }
            });
        }

        // 渲染下载日志表格
        function renderDownloadLogsTable(logs) {
            var rows = '';
            
            // 如果没有数据，显示提示信息
            if (logs.length === 0) {
                rows = `
                    <tr>
                        <td colspan="6" style="text-align: center; color: #999;">
                            暂无下载日志数据
                        </td>
                    </tr>
                `;
            } else {
                for(var i=0;i<logs.length;i++){
                    var log = logs[i];
                    // 下载操作一般都是成功的，除非有特殊错误
                    var statusClass = 'layui-bg-green';
                    var statusText = '成功';
                    rows += `<tr>
                    <td>${log.filename || '未知文件'}</td>
                    <td>${log.username || '未知用户'}</td>
                    <td>${formatDateTime(log.operationTime)}</td>
                    <td>${log.fileSize || '未知'}</td>
                    <td><span class="layui-badge ${statusClass}">${statusText}</span></td>
                    <td>127.0.0.1</td>
                </tr>`;
                }
            }
            
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">文件下载管理</div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>下载用户</th>
                            <th>下载时间</th>
                            <th>文件大小</th>
                            <th>下载状态</th>
                            <th>IP地址</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        </div>
        `);
        }

        // 回收站管理
        function renderFileTrashManage(){
            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">系统回收站管理</div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 40px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px;"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载回收站文件
            loadAdminTrashFiles();
        }

        // 加载管理员回收站文件
        function loadAdminTrashFiles() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping admin trash load');
                return;
            }

            $.ajax({
                url: '/api/admin/trash',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        renderAdminTrashTable(res.data);
                    } else {
                        layer.msg('获取系统回收站文件失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取系统回收站文件失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        window.location.href = '/auth/admin-login';
                    } else {
                        layer.msg('获取系统回收站文件失败', {icon: 2});
                    }
                }
            });
        }

        // 渲染管理员回收站表格
        function renderAdminTrashTable(trashFiles) {
            let rows = '';
            
            if (trashFiles.length === 0) {
                rows = '<tr><td colspan="6" style="text-align: center; color: #999;">系统回收站为空</td></tr>';
            } else {
                for (let i = 0; i < trashFiles.length; i++) {
                    const file = trashFiles[i];
                    const deleteTime = formatDateTime(file.deletedAt || file.updatedAt);
                    const fileSize = formatFileSize(file.fileSize);
                    const encryptIcon = file.encrypted ? '<i class="layui-icon layui-icon-password" style="color: #FF5722;"></i> ' : '';
                    
                    // 计算保留期限（假设30天保留期）
                    const deleteDate = new Date(file.deletedAt || file.updatedAt);
                    const expireDate = new Date(deleteDate.getTime() + 30 * 24 * 60 * 60 * 1000);
                    const now = new Date();
                    const daysLeft = Math.ceil((expireDate - now) / (24 * 60 * 60 * 1000));
                    const expireText = daysLeft > 0 ? `${daysLeft}天后永久删除` : '即将永久删除';
                    
                    rows += `<tr>
                        <td>${encryptIcon}${file.originalFilename}</td>
                        <td>用户ID: ${file.userId}</td>
                        <td>${deleteTime}</td>
                        <td>${fileSize}</td>
                        <td>${expireText}</td>
                        <td>
                            <button class="layui-btn layui-btn-xs layui-btn-normal btn-admin-restore" data-file-id="${file.fileId}">恢复</button>
                            <button class="layui-btn layui-btn-xs layui-btn-danger btn-admin-permanent-delete" data-file-id="${file.fileId}">永久删除</button>
                        </td>
                    </tr>`;
                }
            }

            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">
                系统回收站管理
                <span style="color: #999; font-size: 12px; float: right;">共 ${trashFiles.length} 个已删除文件</span>
            </div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>原所有者</th>
                            <th>删除时间</th>
                            <th>文件大小</th>
                            <th>保留期限</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="admin-trash-table-body">${rows}</tbody>
                </table>
            </div>
        </div>
        `);

            bindAdminTrashActions();
        }

        // 绑定管理员回收站操作事件
        function bindAdminTrashActions() {
            // 管理员恢复文件
            $('.btn-admin-restore').click(function() {
                const fileId = $(this).attr('data-file-id');
                const fileName = $(this).closest('tr').find('td:first').text();
                
                layer.confirm(`确定要恢复文件 "${fileName}" 吗？`, {icon: 3, title:'管理员确认恢复'}, function(index) {
                    adminRestoreFile(fileId);
                    layer.close(index);
                });
            });

            // 管理员永久删除文件
            $('.btn-admin-permanent-delete').click(function() {
                const fileId = $(this).attr('data-file-id');
                const fileName = $(this).closest('tr').find('td:first').text();
                
                layer.confirm(`确定要永久删除文件 "${fileName}" 吗？此操作不可撤销！`, {icon: 2, title:'管理员确认永久删除'}, function(index) {
                    adminPermanentDeleteFile(fileId);
                    layer.close(index);
                });
            });
        }

        // 管理员恢复文件
        function adminRestoreFile(fileId) {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            $.ajax({
                url: `/api/admin/trash/restore/${fileId}`,
                type: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        layer.msg('文件恢复成功', {icon: 1});
                        loadAdminTrashFiles(); // 重新加载回收站
                    } else {
                        layer.msg('文件恢复失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('文件恢复失败', {icon: 2});
                }
            });
        }

        // 管理员永久删除文件
        function adminPermanentDeleteFile(fileId) {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            $.ajax({
                url: `/api/admin/trash/${fileId}`,
                type: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        layer.msg('文件已永久删除', {icon: 1});
                        loadAdminTrashFiles(); // 重新加载回收站
                    } else {
                        layer.msg('永久删除失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('永久删除失败', {icon: 2});
                }
            });
        }

        // 其他功能的占位实现
        function renderStatistics(){ layer.msg('统计分析功能开发中...'); }
        function renderPerformance(){ layer.msg('性能监控功能开发中...'); }
        // 角色权限管理
        function renderUserRoles() {
            if (!checkTokenAndRedirect()) return;
            
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            // 先显示加载状态
            $('#main-container').html(`
                <div class="layui-card">
                    <div class="layui-card-header">
                        <i class="layui-icon layui-icon-username"></i> 角色权限管理
                        <span style="float:right;">
                            <button class="layui-btn layui-btn-sm layui-btn-primary" onclick="renderUserRoles()">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </span>
                    </div>
                    <div class="layui-card-body">
                        <div style="text-align: center; padding: 50px;">
                            <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>
            `);

            // 加载用户角色数据
            $.ajax({
                url: '/api/admin/users',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                timeout: 10000,
                success: function(res) {
                    if (res.success) {
                        const users = res.data;
                        
                        // 统计角色分布
                        const roleStats = {
                            'USER': 0,
                            'ADMIN': 0,
                            'ROOT_ADMIN': 0
                        };
                        
                        users.forEach(user => {
                            if (user.roles && user.roles.length > 0) {
                                user.roles.forEach(role => {
                                    if (roleStats[role] !== undefined) {
                                        roleStats[role]++;
                                    }
                                });
                            } else {
                                // 如果没有角色信息，默认为USER
                                roleStats['USER']++;
                            }
                        });
                        
                        let rows = '';
                        users.forEach(user => {
                            const statusClass = user.isActive ? 'layui-bg-green' : 'layui-bg-red';
                            const statusText = user.isActive ? '正常' : '禁用';
                            const roles = user.roles && user.roles.length > 0 ? user.roles.join(', ') : 'USER';
                            const rolesBadge = generateRolesBadge(user.roles || ['USER']);
                            const createdTime = formatDateTime(user.createdAt);
                            const lastLogin = user.updatedAt ? formatDateTime(user.updatedAt) : '从未登录';
                            
                            rows += `<tr>
                                <td>${user.userId}</td>
                                <td>${user.username}</td>
                                <td>${user.email || '-'}</td>
                                <td>${rolesBadge}</td>
                                <td><span class="layui-badge ${statusClass}">${statusText}</span></td>
                                <td>${createdTime}</td>
                                <td>${lastLogin}</td>
                                <td>
                                    <button class="layui-btn layui-btn-xs layui-btn-normal" onclick="viewUserDetails(${user.userId}, '${user.userType}')">
                                        <i class="layui-icon layui-icon-about"></i> 详情
                                    </button>
                                </td>
                            </tr>`;
                        });
                        
                        if (rows === '') {
                            rows = '<tr><td colspan="8">暂无用户数据</td></tr>';
                        }
                        
                        $('#main-container').html(`
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <i class="layui-icon layui-icon-username"></i> 角色权限管理
                                    <span style="float:right;">
                                        <button class="layui-btn layui-btn-sm layui-btn-primary" onclick="renderUserRoles()">
                                            <i class="layui-icon layui-icon-refresh"></i> 刷新
                                        </button>
                                    </span>
                                </div>
                                <div class="layui-card-body">
                                    <!-- 角色统计卡片 -->
                                    <div class="layui-row layui-col-space15" style="margin-bottom: 20px;">
                                        <div class="layui-col-md4">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <i class="layui-icon layui-icon-user" style="font-size: 30px; color: #1E9FFF;"></i>
                                                    <p style="margin: 10px 0 5px 0; font-size: 24px; font-weight: bold;">${roleStats.USER}</p>
                                                    <p style="margin: 0; color: #666;">普通用户</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="layui-col-md4">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <i class="layui-icon layui-icon-group" style="font-size: 30px; color: #FFB800;"></i>
                                                    <p style="margin: 10px 0 5px 0; font-size: 24px; font-weight: bold;">${roleStats.ADMIN}</p>
                                                    <p style="margin: 0; color: #666;">管理员</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="layui-col-md4">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <i class="layui-icon layui-icon-senior" style="font-size: 30px; color: #FF5722;"></i>
                                                    <p style="margin: 10px 0 5px 0; font-size: 24px; font-weight: bold;">${roleStats.ROOT_ADMIN}</p>
                                                    <p style="margin: 0; color: #666;">系统管理员</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- 用户角色列表 -->
                                    <table class="layui-table" lay-size="sm">
                                        <thead>
                                            <tr>
                                                <th>用户ID</th>
                                                <th>用户名</th>
                                                <th>邮箱</th>
                                                <th>角色</th>
                                                <th>状态</th>
                                                <th>注册时间</th>
                                                <th>最后登录</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>${rows}</tbody>
                                    </table>
                                    
                                    <div class="layui-card" style="margin-top: 20px;">
                                        <div class="layui-card-header">角色权限说明</div>
                                        <div class="layui-card-body">
                                            <div class="layui-row layui-col-space15">
                                                <div class="layui-col-md4">
                                                    <p><span class="layui-badge layui-bg-blue">USER</span> <strong>普通用户</strong></p>
                                                    <ul style="margin-left: 20px; font-size: 12px; color: #666;">
                                                        <li>文件上传、下载</li>
                                                        <li>个人文件管理</li>
                                                        <li>基础系统功能</li>
                                                    </ul>
                                                </div>
                                                <div class="layui-col-md4">
                                                    <p><span class="layui-badge layui-bg-orange">ADMIN</span> <strong>管理员</strong></p>
                                                    <ul style="margin-left: 20px; font-size: 12px; color: #666;">
                                                        <li>用户管理</li>
                                                        <li>系统监控</li>
                                                        <li>日志查看</li>
                                                        <li>文件管理</li>
                                                    </ul>
                                                </div>
                                                <div class="layui-col-md4">
                                                    <p><span class="layui-badge layui-bg-red">ROOT_ADMIN</span> <strong>系统管理员</strong></p>
                                                    <ul style="margin-left: 20px; font-size: 12px; color: #666;">
                                                        <li>所有管理员权限</li>
                                                        <li>系统配置</li>
                                                        <li>备份管理</li>
                                                        <li>安全设置</li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `);
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    console.error('加载角色权限失败:', xhr, textStatus, errorThrown);
                    
                    let errorMessage = '加载角色权限失败';
                    
                    if (textStatus === 'timeout') {
                        errorMessage = '请求超时，请重试';
                    } else if (xhr.status === 401) {
                        errorMessage = '登录已过期，请重新登录';
                        localStorage.removeItem('token');
                        window.location.href = '/login';
                        return;
                    } else if (xhr.status === 403) {
                        errorMessage = '权限不足';
                    } else if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    } else if (xhr.status === 0) {
                        errorMessage = '网络连接失败，请检查网络';
                    }
                    
                    $('#main-container').html(`
                        <div class="layui-card">
                            <div class="layui-card-header">角色权限管理</div>
                            <div class="layui-card-body">
                                <div style="text-align: center; padding: 50px;">
                                    <i class="layui-icon layui-icon-face-cry" style="font-size: 60px; color: #ff5722;"></i>
                                    <p style="font-size: 16px; margin-top: 20px;">${errorMessage}</p>
                                    <button class="layui-btn layui-btn-primary" onclick="renderUserRoles()">
                                        <i class="layui-icon layui-icon-refresh"></i> 重新加载
                                    </button>
                                </div>
                            </div>
                        </div>
                    `);
                    
                    layer.msg(errorMessage, {icon: 2, time: 3000});
                }
            });
        }
        
        // 生成角色徽章
        function generateRolesBadge(roles) {
            if (!roles || roles.length === 0) {
                return '<span class="layui-badge layui-bg-blue">USER</span>';
            }
            
            const roleColors = {
                'USER': 'layui-bg-blue',
                'ADMIN': 'layui-bg-orange', 
                'ROOT_ADMIN': 'layui-bg-red'
            };
            
            return roles.map(role => {
                const colorClass = roleColors[role] || 'layui-bg-gray';
                return `<span class="layui-badge ${colorClass}">${role}</span>`;
            }).join(' ');
        }
        
        // 查看用户详情
        function viewUserDetails(userId, userType) {
            if (!checkTokenAndRedirect()) return;
            
            const token = getToken();
            if (!token) return;
            
            const loadingIndex = layer.load(1);
            
            // 构建URL，如果有userType参数则添加到查询参数中
            let url = `/api/admin/users/${userId}`;
            if (userType && userType !== 'USER') {
                url += `?userType=${userType}`;
            }
            
            $.ajax({
                url: url,
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                timeout: 10000,
                success: function(res) {
                    layer.close(loadingIndex);
                    
                    if (res.success) {
                        const user = res.data.user;
                        const fileStats = res.data.fileStats;
                        const roles = user.roles && user.roles.length > 0 ? user.roles.join(', ') : 'USER';
                        const statusText = user.isActive ? '正常' : '禁用';
                        const statusColor = user.isActive ? '#5FB878' : '#FF5722';
                        
                        layer.open({
                            type: 1,
                            title: '用户详细信息',
                            area: ['500px', '600px'],
                            content: `
                                <div style="padding: 20px;">
                                    <div class="layui-form">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">用户ID:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${user.userId}</div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">用户名:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${user.username}</div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">邮箱:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${user.email || '未设置'}</div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">角色:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${generateRolesBadge(user.roles || ['USER'])}</div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">状态:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">
                                                    <span style="color: ${statusColor}; font-weight: bold;">${statusText}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">注册时间:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${formatDateTime(user.createdAt)}</div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">最后登录:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${user.updatedAt ? formatDateTime(user.updatedAt) : '从未登录'}</div>
                                            </div>
                                        </div>
                                        
                                        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                                            <legend>文件统计</legend>
                                        </fieldset>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">文件总数:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${fileStats.totalFiles || 0} 个</div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">总大小:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${formatFileSize(fileStats.totalSize || 0)}</div>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">已删除:</label>
                                            <div class="layui-input-block">
                                                <div class="layui-form-mid">${fileStats.deletedFiles || 0} 个</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `
                        });
                    } else {
                        layer.msg(res.message || '获取用户详情失败', {icon: 2});
                    }
                },
                error: function(xhr) {
                    layer.close(loadingIndex);
                    console.error('获取用户详情失败:', xhr);
                    layer.msg('获取用户详情失败', {icon: 2});
                }
            });
        }
        // 用户活动监控
        function renderUserActivity() {
            if (!checkTokenAndRedirect()) return;
            
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            // 先显示加载状态
            $('#main-container').html(`
                <div class="layui-card">
                    <div class="layui-card-header">
                        <i class="layui-icon layui-icon-chart"></i> 用户活动监控
                        <span style="float:right;">
                            <button class="layui-btn layui-btn-sm layui-btn-primary" onclick="renderUserActivity()">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </span>
                    </div>
                    <div class="layui-card-body">
                        <div style="text-align: center; padding: 50px;">
                            <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>
            `);

            // 并行加载多个数据源
            Promise.all([
                loadUserOperationLogs(token),
                loadFileOperationLogs(token),
                loadLogOverview(token),
                loadUserList(token)
            ]).then(([userLogs, fileLogs, overview, users]) => {
                renderUserActivityPage(userLogs, fileLogs, overview, users);
            }).catch(error => {
                console.error('加载用户活动数据失败:', error);
                showUserActivityError(error.message || '加载用户活动数据失败');
            });
        }
        
        // 加载用户操作日志
        function loadUserOperationLogs(token) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: '/api/admin/logs/user-operations?limit=50',
                    type: 'GET',
                    headers: { 'Authorization': 'Bearer ' + token },
                    timeout: 10000,
                    success: function(res) {
                        if (res.success) {
                            resolve(res.data || []);
                        } else {
                            reject(new Error(res.message || '获取用户操作日志失败'));
                        }
                    },
                    error: function(xhr) {
                        reject(new Error('获取用户操作日志失败'));
                    }
                });
            });
        }
        
        // 加载文件操作日志
        function loadFileOperationLogs(token) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: '/api/admin/logs/file-operations?limit=30',
                    type: 'GET',
                    headers: { 'Authorization': 'Bearer ' + token },
                    timeout: 10000,
                    success: function(res) {
                        if (res.success) {
                            resolve(res.data || []);
                        } else {
                            reject(new Error(res.message || '获取文件操作日志失败'));
                        }
                    },
                    error: function(xhr) {
                        reject(new Error('获取文件操作日志失败'));
                    }
                });
            });
        }
        
        // 加载日志概览
        function loadLogOverview(token) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: '/api/admin/logs/overview',
                    type: 'GET',
                    headers: { 'Authorization': 'Bearer ' + token },
                    timeout: 10000,
                    success: function(res) {
                        if (res.success) {
                            resolve(res.data || {});
                        } else {
                            reject(new Error(res.message || '获取日志概览失败'));
                        }
                    },
                    error: function(xhr) {
                        reject(new Error('获取日志概览失败'));
                    }
                });
            });
        }
        
        // 加载用户列表（用于用户名映射）
        function loadUserList(token) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: '/api/admin/users',
                    type: 'GET',
                    headers: { 'Authorization': 'Bearer ' + token },
                    timeout: 10000,
                    success: function(res) {
                        if (res.success) {
                            resolve(res.data || []);
                        } else {
                            reject(new Error(res.message || '获取用户列表失败'));
                        }
                    },
                    error: function(xhr) {
                        reject(new Error('获取用户列表失败'));
                    }
                });
            });
        }
        
        // 渲染用户活动页面
        function renderUserActivityPage(userLogs, fileLogs, overview, users) {
            // 创建用户ID到用户名的映射
            const userMap = {};
            users.forEach(user => {
                userMap[user.userId] = user;
            });
            
            // 统计活动操作类型
            const userOpStats = {};
            const fileOpStats = {};
            
            userLogs.forEach(log => {
                userOpStats[log.operationType] = (userOpStats[log.operationType] || 0) + 1;
            });
            
            fileLogs.forEach(log => {
                fileOpStats[log.operationType] = (fileOpStats[log.operationType] || 0) + 1;
            });
            
            // 生成用户操作日志表格
            let userLogRows = '';
            userLogs.slice(0, 20).forEach(log => {
                const user = userMap[log.userId] || { username: '未知用户', email: '' };
                const operationTime = formatDateTime(log.operationTime);
                const operationType = getOperationTypeLabel(log.operationType);
                const operationIcon = getOperationTypeIcon(log.operationType);
                
                userLogRows += `<tr>
                    <td>${operationTime}</td>
                    <td>
                        <span style="display: inline-block; margin-right: 8px;">${operationIcon}</span>
                        ${operationType}
                    </td>
                    <td>
                        <span class="layui-badge layui-bg-blue">${user.username}</span>
                        <small style="color: #666; margin-left: 5px;">${user.email || ''}</small>
                    </td>
                    <td>${log.operation || '-'}</td>
                    <td>${log.operationDetails || '-'}</td>
                    <td>
                        <button class="layui-btn layui-btn-xs layui-btn-primary" onclick="viewUserActivities(${log.userId})">
                            查看该用户活动
                        </button>
                    </td>
                </tr>`;
            });
            
            if (userLogRows === '') {
                userLogRows = '<tr><td colspan="6">暂无用户操作记录</td></tr>';
            }
            
            // 生成文件操作日志表格
            let fileLogRows = '';
            fileLogs.slice(0, 15).forEach(log => {
                const user = userMap[log.userId] || { username: '未知用户' };
                const operationTime = formatDateTime(log.operationTime);
                const operationType = getOperationTypeLabel(log.operationType);
                const operationIcon = getOperationTypeIcon(log.operationType);
                
                fileLogRows += `<tr>
                    <td>${operationTime}</td>
                    <td>
                        <span style="display: inline-block; margin-right: 8px;">${operationIcon}</span>
                        ${operationType}
                    </td>
                    <td><span class="layui-badge layui-bg-blue">${user.username}</span></td>
                    <td>文件ID: ${log.fileId || '-'}</td>
                    <td>${log.operationDetails || '-'}</td>
                </tr>`;
            });
            
            if (fileLogRows === '') {
                fileLogRows = '<tr><td colspan="5">暂无文件操作记录</td></tr>';
            }
            
            // 渲染页面
            $('#main-container').html(`
                <div class="layui-card">
                    <div class="layui-card-header">
                        <i class="layui-icon layui-icon-chart"></i> 用户活动监控
                        <span style="float:right;">
                            <button class="layui-btn layui-btn-sm layui-btn-primary" onclick="renderUserActivity()">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </span>
                    </div>
                    <div class="layui-card-body">
                        <!-- 活动统计概览 -->
                        <div class="layui-row layui-col-space15" style="margin-bottom: 20px;">
                            <div class="layui-col-md3">
                                <div class="layui-card">
                                    <div class="layui-card-body" style="text-align: center;">
                                        <i class="layui-icon layui-icon-chart-screen" style="font-size: 30px; color: #1E9FFF;"></i>
                                        <p style="margin: 10px 0 5px 0; font-size: 24px; font-weight: bold;">${overview.todayUserOperations || 0}</p>
                                        <p style="margin: 0; color: #666;">今日用户操作</p>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-card">
                                    <div class="layui-card-body" style="text-align: center;">
                                        <i class="layui-icon layui-icon-file" style="font-size: 30px; color: #5FB878;"></i>
                                        <p style="margin: 10px 0 5px 0; font-size: 24px; font-weight: bold;">${overview.todayFileOperations || 0}</p>
                                        <p style="margin: 0; color: #666;">今日文件操作</p>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-card">
                                    <div class="layui-card-body" style="text-align: center;">
                                        <i class="layui-icon layui-icon-user" style="font-size: 30px; color: #FFB800;"></i>
                                        <p style="margin: 10px 0 5px 0; font-size: 24px; font-weight: bold;">${Object.keys(userMap).length}</p>
                                        <p style="margin: 0; color: #666;">活跃用户</p>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-card">
                                    <div class="layui-card-body" style="text-align: center;">
                                        <i class="layui-icon layui-icon-tabs" style="font-size: 30px; color: #FF5722;"></i>
                                        <p style="margin: 10px 0 5px 0; font-size: 24px; font-weight: bold;">${userLogs.length + fileLogs.length}</p>
                                        <p style="margin: 0; color: #666;">总操作记录</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 最近用户操作日志 -->
                        <div class="layui-card" style="margin-bottom: 20px;">
                            <div class="layui-card-header">
                                <i class="layui-icon layui-icon-username"></i> 最近用户操作 (最新20条)
                            </div>
                            <div class="layui-card-body">
                                <table class="layui-table" lay-size="sm">
                                    <thead>
                                        <tr>
                                            <th>操作时间</th>
                                            <th>操作类型</th>
                                            <th>用户</th>
                                            <th>操作描述</th>
                                            <th>详细信息</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>${userLogRows}</tbody>
                                </table>
                            </div>
                        </div>
                        
                        <!-- 最近文件操作日志 -->
                        <div class="layui-card">
                            <div class="layui-card-header">
                                <i class="layui-icon layui-icon-file"></i> 最近文件操作 (最新15条)
                            </div>
                            <div class="layui-card-body">
                                <table class="layui-table" lay-size="sm">
                                    <thead>
                                        <tr>
                                            <th>操作时间</th>
                                            <th>操作类型</th>
                                            <th>用户</th>
                                            <th>文件信息</th>
                                            <th>详细信息</th>
                                        </tr>
                                    </thead>
                                    <tbody>${fileLogRows}</tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            `);
        }
        
        // 获取操作类型标签
        function getOperationTypeLabel(operationType) {
            const typeLabels = {
                'LOGIN': '用户登录',
                'LOGOUT': '用户退出',
                'REGISTER': '用户注册',
                'PASSWORD_RESET': '密码重置',
                'STATUS_CHANGE': '状态变更',
                'TOKEN_REVOKE': '令牌撤销',
                'USER_DELETE': '删除用户',
                'DELETE_FAILED': '删除失败',
                'UPLOAD': '文件上传',
                'DOWNLOAD': '文件下载',
                'DELETE': '文件删除',
                'SHARE': '文件分享',
                'MODIFY': '文件修改',
                'RESTORE': '文件恢复',
                'SYSTEM': '系统操作'
            };
            return typeLabels[operationType] || operationType || '未知操作';
        }
        
        // 获取操作类型图标
        function getOperationTypeIcon(operationType) {
            const typeIcons = {
                'LOGIN': '🔑',
                'LOGOUT': '🚪',
                'REGISTER': '👤',
                'PASSWORD_RESET': '🔒',
                'STATUS_CHANGE': '⚡',
                'TOKEN_REVOKE': '🚫',
                'USER_DELETE': '🗑️',
                'DELETE_FAILED': '❌',
                'UPLOAD': '⬆️',
                'DOWNLOAD': '⬇️',
                'DELETE': '🗑️',
                'SHARE': '🔗',
                'MODIFY': '✏️',
                'RESTORE': '♻️',
                'SYSTEM': '⚙️'
            };
            return typeIcons[operationType] || '📝';
        }
        
        // 查看特定用户的活动记录
        function viewUserActivities(userId) {
            if (!checkTokenAndRedirect()) return;
            
            const token = getToken();
            if (!token) return;
            
            const loadingIndex = layer.load(1);
            
            // 加载用户详情和活动记录
            Promise.all([
                new Promise((resolve, reject) => {
                    $.ajax({
                        url: `/api/admin/users/${userId}`,
                        type: 'GET',
                        headers: { 'Authorization': 'Bearer ' + token },
                        success: res => res.success ? resolve(res.data) : reject(new Error(res.message)),
                        error: () => reject(new Error('获取用户信息失败'))
                    });
                }),
                new Promise((resolve, reject) => {
                    $.ajax({
                        url: `/api/admin/logs/user-operations?userId=${userId}&limit=100`,
                        type: 'GET',
                        headers: { 'Authorization': 'Bearer ' + token },
                        success: res => res.success ? resolve(res.data) : reject(new Error(res.message)),
                        error: () => reject(new Error('获取用户活动失败'))
                    });
                })
            ]).then(([userDetails, userLogs]) => {
                layer.close(loadingIndex);
                
                const user = userDetails.user;
                const fileStats = userDetails.fileStats;
                
                let activityRows = '';
                userLogs.forEach(log => {
                    const operationTime = formatDateTime(log.operationTime);
                    const operationType = getOperationTypeLabel(log.operationType);
                    const operationIcon = getOperationTypeIcon(log.operationType);
                    
                    activityRows += `<tr>
                        <td>${operationTime}</td>
                        <td>
                            <span style="margin-right: 8px;">${operationIcon}</span>
                            ${operationType}
                        </td>
                        <td>${log.operation || '-'}</td>
                        <td>${log.operationDetails || '-'}</td>
                    </tr>`;
                });
                
                if (activityRows === '') {
                    activityRows = '<tr><td colspan="4">该用户暂无活动记录</td></tr>';
                }
                
                layer.open({
                    type: 1,
                    title: `用户活动记录 - ${user.username}`,
                    area: ['800px', '600px'],
                    content: `
                        <div style="padding: 20px;">
                            <div class="layui-card" style="margin-bottom: 15px;">
                                <div class="layui-card-header">用户基本信息</div>
                                <div class="layui-card-body">
                                    <div class="layui-row">
                                        <div class="layui-col-md6">
                                            <p><strong>用户名:</strong> ${user.username}</p>
                                            <p><strong>邮箱:</strong> ${user.email || '未设置'}</p>
                                            <p><strong>角色:</strong> ${generateRolesBadge(user.roles || ['USER'])}</p>
                                        </div>
                                        <div class="layui-col-md6">
                                            <p><strong>文件总数:</strong> ${fileStats.totalFiles || 0} 个</p>
                                            <p><strong>存储大小:</strong> ${formatFileSize(fileStats.totalSize || 0)}</p>
                                            <p><strong>活动记录:</strong> ${userLogs.length} 条</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="layui-card">
                                <div class="layui-card-header">活动记录 (最近100条)</div>
                                <div class="layui-card-body" style="max-height: 350px; overflow-y: auto;">
                                    <table class="layui-table" lay-size="sm">
                                        <thead>
                                            <tr>
                                                <th>时间</th>
                                                <th>操作类型</th>
                                                <th>操作描述</th>
                                                <th>详细信息</th>
                                            </tr>
                                        </thead>
                                        <tbody>${activityRows}</tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    `
                });
                
            }).catch(error => {
                layer.close(loadingIndex);
                console.error('获取用户活动记录失败:', error);
                layer.msg('获取用户活动记录失败: ' + error.message, {icon: 2});
            });
        }
        
        // 显示用户活动错误页面
        function showUserActivityError(errorMessage) {
            $('#main-container').html(`
                <div class="layui-card">
                    <div class="layui-card-header">用户活动监控</div>
                    <div class="layui-card-body">
                        <div style="text-align: center; padding: 50px;">
                            <i class="layui-icon layui-icon-face-cry" style="font-size: 60px; color: #ff5722;"></i>
                            <p style="font-size: 16px; margin-top: 20px;">${errorMessage}</p>
                            <button class="layui-btn layui-btn-primary" onclick="renderUserActivity()">
                                <i class="layui-icon layui-icon-refresh"></i> 重新加载
                            </button>
                        </div>
                    </div>
                </div>
            `);
        }
        function renderFileIntegrity(){ layer.msg('完整性检查功能开发中...'); }
        function renderStorageQuota(){ layer.msg('存储配额功能开发中...'); }
        function renderSecurityConfig(){ layer.msg('安全配置功能开发中...'); }
        function renderBackupConfig() {
            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">备份配置管理</div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 40px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px;"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载备份配置
            loadBackupConfig();
        }

        // 加载备份配置
        function loadBackupConfig() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping backup config load');
                return;
            }

            $.ajax({
                url: '/api/admin/backup/config',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        renderBackupConfigForm(res.data);
                    } else {
                        layer.msg('获取备份配置失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取备份配置失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        window.location.href = '/auth/admin-login';
                    } else {
                        layer.msg('获取备份配置失败', {icon: 2});
                    }
                }
            });
        }

        // 渲染备份配置表单
        function renderBackupConfigForm(config) {
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">备份配置管理</div>
            <div class="layui-card-body">
                <form class="layui-form" lay-filter="backupConfigForm">
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">备份服务</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="enabled" title="启用备份服务" ${config.enabled ? 'checked' : ''}>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">自动备份</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="autoBackupEnabled" title="启用自动备份" ${config.autoBackupEnabled ? 'checked' : ''}>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">备份路径</label>
                                <div class="layui-input-block">
                                    <input type="text" name="backupBasePath" value="${config.backupBasePath || ''}" placeholder="请输入备份存储路径" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">最大备份大小</label>
                                <div class="layui-input-block">
                                    <input type="number" name="maxBackupSize" value="${config.maxBackupSize || ''}" placeholder="MB" class="layui-input">
                                    <div class="layui-form-mid layui-word-aux">单位：MB</div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">保留天数</label>
                                <div class="layui-input-block">
                                    <input type="number" name="retentionDays" value="${config.retentionDays || ''}" placeholder="天" class="layui-input">
                                    <div class="layui-form-mid layui-word-aux">备份文件保留天数</div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">自动备份间隔</label>
                                <div class="layui-input-block">
                                    <input type="number" name="autoBackupInterval" value="${config.autoBackupInterval || ''}" placeholder="小时" class="layui-input">
                                    <div class="layui-form-mid layui-word-aux">单位：小时</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="saveBackupConfig">保存配置</button>
                            <button type="button" class="layui-btn layui-btn-primary" onclick="loadBackupConfig()">重置</button>
                        </div>
                    </div>
                </form>
                
                <hr>
                
                <div class="layui-card">
                    <div class="layui-card-header">备份列表</div>
                    <div class="layui-card-body">
                        <div id="backup-list-container">
                            <div style="text-align: center; padding: 20px;">
                                <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 20px;"></i>
                                <p>加载备份列表...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        `);

            // 重新渲染表单
            layui.form.render();
            
            // 绑定表单提交事件
            bindBackupConfigForm();
            
            // 加载备份列表
            loadBackupList();
        }

        // 绑定备份配置表单事件
        function bindBackupConfigForm() {
            layui.form.on('submit(saveBackupConfig)', function(data) {
                saveBackupConfig(data.field);
                return false;
            });
        }

        // 保存备份配置
        function saveBackupConfig(formData) {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            // 处理复选框值
            formData.enabled = formData.enabled === 'on';
            formData.autoBackupEnabled = formData.autoBackupEnabled === 'on';
            
            // 转换数字类型
            formData.maxBackupSize = parseInt(formData.maxBackupSize) || 0;
            formData.retentionDays = parseInt(formData.retentionDays) || 0;
            formData.autoBackupInterval = parseInt(formData.autoBackupInterval) || 0;

            $.ajax({
                url: '/api/admin/backup/config',
                type: 'PUT',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify(formData),
                success: function(res) {
                    if (res.success) {
                        layer.msg('备份配置保存成功', {icon: 1});
                    } else {
                        layer.msg('备份配置保存失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('备份配置保存失败', {icon: 2});
                }
            });
        }

        // 加载备份列表
        function loadBackupList() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping backup list load');
                return;
            }

            $.ajax({
                url: '/api/admin/backup/list',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        renderBackupList(res.data);
                    } else {
                        $('#backup-list-container').html('<p style="text-align: center; color: #999;">获取备份列表失败</p>');
                    }
                },
                error: function() {
                    $('#backup-list-container').html('<p style="text-align: center; color: #999;">获取备份列表失败</p>');
                }
            });
        }

        // 渲染备份列表
        function renderBackupList(backups) {
            let rows = '';
            
            if (backups.length === 0) {
                rows = '<tr><td colspan="5" style="text-align: center; color: #999;">暂无备份记录</td></tr>';
            } else {
                for (let i = 0; i < backups.length; i++) {
                    const backup = backups[i];
                    const backupTime = formatDateTime(backup.createdAt);
                    const backupSize = formatFileSize(backup.backupFileSize);
                    
                    rows += `<tr>
                        <td>文件ID: ${backup.fileId}</td>
                        <td>${backup.backupType || '自动备份'}</td>
                        <td>${backupTime}</td>
                        <td>${backupSize}</td>
                        <td>
                            <button class="layui-btn layui-btn-xs layui-btn-normal">查看</button>
                        </td>
                    </tr>`;
                }
            }

            $('#backup-list-container').html(`
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件信息</th>
                            <th>备份类型</th>
                            <th>备份时间</th>
                            <th>备份大小</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            `);
        }

        // 创建管理员对话框
        function showCreateAdminDialog(){
            layer.open({
                type: 1,
                area: ['520px', '480px'],
                title: '🛡️ 创建管理员账户',
                content: `<form class="layui-form" style="padding:24px;">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" id="admin-username" required lay-verify="required|username" placeholder="请输入管理员用户名（3-20位字母数字）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" id="admin-password" required lay-verify="required|adminPassword" placeholder="请输入密码（至少8位）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱</label>
                    <div class="layui-input-block">
                        <input type="email" name="email" id="admin-email" required lay-verify="required|email" placeholder="请输入邮箱地址" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">部门</label>
                    <div class="layui-input-block">
                        <input type="text" name="department" id="admin-department" placeholder="请输入所属部门（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <textarea name="remarks" id="admin-remarks" placeholder="请输入备注信息（可选）" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item" style="text-align: center; padding-top: 10px;">
                    <button class="layui-btn layui-btn-danger" id="do-create-admin">创建管理员账户</button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                </div>
            </form>`,
                success: function(){
                    form.render();
                    
                    // 自定义验证规则
                    form.verify({
                        username: function(value){
                            if(!/^[a-zA-Z0-9]{3,20}$/.test(value)){
                                return '用户名必须3-20位，只能包含字母和数字';
                            }
                        },
                        adminPassword: function(value){
                            if(value.length < 8){
                                return '管理员密码长度不能少于8位';
                            }
                        }
                    });
                    
                    // 创建管理员提交
                    $('#do-create-admin').click(function(e){
                        e.preventDefault();
                        
                        var formData = {
                            username: $('#admin-username').val(),
                            password: $('#admin-password').val(),
                            email: $('#admin-email').val(),
                            department: $('#admin-department').val(),
                            remarks: $('#admin-remarks').val()
                        };
                        
                        // 验证必填项
                        if(!formData.username || !formData.password || !formData.email){
                            layer.msg('请填写所有必填项', {icon: 2});
                            return;
                        }
                        
                        // 发送创建请求
                        $.ajax({
                            url: '/auth/create-admin',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(formData),
                            success: function(response) {
                                if (response.success) {
                                    layer.alert(response.message, {
                                        icon: 1,
                                        title: '创建成功'
                                    }, function(index) {
                                        layer.close(index);
                                        layer.closeAll();
                                        renderUserList(); // 刷新用户列表
                                    });
                                } else {
                                    layer.msg(response.message, {icon: 2, time: 3000});
                                }
                            },
                            error: function() {
                                layer.msg('网络连接异常，请稍后再试', {icon: 2, time: 3000});
                            }
                        });
                    });
                }
            });
        }
    });
</script>
</body>
</html>